package myauctioneer.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import myauctioneer.App;
import myauctioneer.dto.Article;
import myauctioneer.dto.RatingDetail;
import myauctioneer.dto.User;
import myauctioneer.dto.Bid;
import myauctioneer.dao.ArticleDAO;
import myauctioneer.dao.BidDAO;
import myauctioneer.service.ArticleService;
import myauctioneer.service.SalesService;

/**
 * Servlet implementation class SalesServlet
 */
@javax.servlet.annotation.WebServlet("/sales/*")
public class SalesServlet extends DefaultServlet {
	private static final long serialVersionUID = 1L;
	
	public void scoreBuyerAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		
		long now = System.currentTimeMillis();
		Date date = new Date(now);
		SimpleDateFormat formatter = new SimpleDateFormat(
				"dd-MMM-yyyy HH:mm");
		
		int articleId;
		String labeling, note, time, type;
		
		articleId = Integer.parseInt(request.getParameter("id"));
		labeling = request.getParameter("labeling");
		note = request.getParameter("note");
		time = formatter.format(date);
		type = request.getParameter("type");

		if ((new myauctioneer.service.SalesService()).placeRatingDetail(labeling, note, time)) {
			RatingDetail ratingDetail = (new myauctioneer.service.SalesService()).loadRatingDetailByLabelingNote(labeling, note);
			
			if ((new myauctioneer.service.SalesService()).placeRating(user.getUserId(), articleId, ratingDetail.getRatingDetailId(), type)) {
				request.setAttribute("title", "Buyer rating created");
				request.setAttribute("content", "The buyer rating is now created.");
				request.setAttribute("template", "success.jsp");
			} else {
				request.setAttribute("template", "scoreBuyer.jsp");
			}
		} else {
			request.setAttribute("template", "scoreBuyer.jsp");
		}
	}
	
	public void scoreSellerAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		
		long now = System.currentTimeMillis();
		Date date = new Date(now);
		SimpleDateFormat formatter = new SimpleDateFormat(
				"dd-MMM-yyyy HH:mm");
		
		int articleId;
		String labeling, note, time, type;
		
		articleId = Integer.parseInt(request.getParameter("id"));
		labeling = request.getParameter("labeling");
		note = request.getParameter("note");
		time = formatter.format(date);
		type = request.getParameter("type");

		if ((new myauctioneer.service.SalesService()).placeRatingDetail(labeling, note, time)) {
			RatingDetail ratingDetail = (new myauctioneer.service.SalesService()).loadRatingDetailByLabelingNote(labeling, note);
			
			if ((new myauctioneer.service.SalesService()).placeRating(user.getUserId(), articleId, ratingDetail.getRatingDetailId(), type)) {
				request.setAttribute("title", "Seller rating created");
				request.setAttribute("content", "The seller rating is now created.");
				request.setAttribute("template", "success.jsp");
			} else {
				request.setAttribute("template", "scoreSeller.jsp");
			}
		} else {
			request.setAttribute("template", "scoreSeller.jsp");
		}
	}
	
	public void scoreArticleAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		
		long now = System.currentTimeMillis();
		Date date = new Date(now);
		SimpleDateFormat formatter = new SimpleDateFormat(
				"dd-MMM-yyyy HH:mm");
		
		int articleId;
		String labeling, note, time, type;
		
		articleId = Integer.parseInt(request.getParameter("id"));
		labeling = request.getParameter("labeling");
		note = request.getParameter("note");
		time = formatter.format(date);
		type = request.getParameter("type");

		if ((new myauctioneer.service.SalesService()).placeRatingDetail(labeling, note, time)) {
			RatingDetail ratingDetail = (new myauctioneer.service.SalesService()).loadRatingDetailByLabelingNote(labeling, note);
			
			if ((new myauctioneer.service.SalesService()).placeRating(user.getUserId(), articleId, ratingDetail.getRatingDetailId(), type)) {
				request.setAttribute("title", "Article rating created");
				request.setAttribute("content", "The article rating is now created.");
				request.setAttribute("template", "success.jsp");
			} else {
				request.setAttribute("template", "scoreArticle.jsp");
			}
		} else {
			request.setAttribute("template", "scoreArticle.jsp");
		}
	}

	public void bidBuyAction(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		User user = (User) request.getSession().getAttribute("user");
		BidDAO bidDao = new BidDAO();
		ArticleDAO articleDao = new ArticleDAO();

		request.setAttribute("title", "Error:");
		request.setAttribute("template", "success.jsp");

		if(user == null) {
			request.setAttribute("content", "Please login first.");
			return;
		}

		Article a = articleDao.loadArticleByArticleId(
				Integer.parseInt(request.getParameter("id")));

		if(! a.isValid()) {
			request.setAttribute("content", "Article is no longer on sale.");
			return;
		}

		double amount = 0;

		if(a.getSaleType().equals("directSale")) {
			amount = a.getPrice();
		}
		else {
			amount = Double.parseDouble(request.getParameter("amount"));
			double minAmount = a.getPrice();

			if(a.getFinalBid() > 0)
				minAmount = bidDao.loadBidByBidId(a.getFinalBid()).getAmount()
					+ Double.parseDouble(App.getProperty("bid.increment_min", "0.01"));

			if(minAmount > amount) {
				request.setAttribute("content", "Your bid amount not sufficient, " +
					"minimum bid is " + minAmount + " €");
				return;
			}
		}

		Bid b = new Bid();
		b.setAmount(amount);
		b.setUserId(user.getUserId());
		b.setArticleId(a.getArticleId());
		bidDao.saveBid(b);

		App.getLogger().info("Bid saved: " + b.getBidId());

		a.setFinalBid(b.getBidId());
		articleDao.saveArticle(a);

		request.setAttribute("title", "Successfull:");
		request.setAttribute("content", "Your bid is accepted.");
	}
}
